package com.gzzz.bean.impl;

import com.gzzz.bean.Input;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

/**
 * className: SocketInput
 * Package : com.gzzz.bean.impl
 * Description:
 *
 * @Author gzzz
 * @Create 2023/12/5 17:01
 * @Version 1.0
 */
public class SocketInput implements Input {

    /**
     * 启动socket的server
     * @return 输入流
     */
    @Override
    public InputStream read() {
        Socket socket = null;
        InputStream is = null;
        try {
            //读取配置文件获取端口号
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("socket.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            int port = Integer.parseInt(properties.getProperty("port"));
            //创建ServerSocket
            ServerSocket serverSocket = new ServerSocket(port);

            //接受客户端的socket：accept()
            System.out.println("开始接受数据");
            socket = serverSocket.accept();

            //通过Socket获取一个输入流
            is = socket.getInputStream();
            return is;
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 不能在这里关闭socket，否则流也会关闭，而还没开始循环位移
         */
        return null;
    }
}
